<template>
	<view>
		<form>
			<view class="cu-form-group margin-top">
				<view class="title">标题</view>
				<input placeholder="帖子标题" name="input" v-model="title"></input>
			</view>
			<view class="cu-form-group margin-top">
				<textarea maxlength="-1" v-model="content" placeholder="帖子内容..."></textarea>
			</view>
			<view class="cu-bar bg-white margin-top">
				<view class="action">
					图片/视频上传
				</view>
				<view class="action">
					{{num}}/4
				</view>
			</view>
			<view class="cu-form-group">
				<view class="grid col-4 grid-square flex-sub">
					<view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage" :data-url="imgList[index]">
						<image :src="imgList[index]"></image>
						<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
							<text class='cuIcon-close'></text>
						</view>
					</view>
					<view class="bg-img" v-if="src">
						<video id="myVideo" :src="src" class="video" :controls="false" @play="play" show-progress="false" show-play-btn="false"></video>
						<view class="cu-tag bg-red" @tap.stop="Delvideo" :data-index="index">
							<text class='cuIcon-close'></text>
						</view>
					</view>
					<view class="solids" @tap="ChooseImage" v-if="num<4">
						<text class='cuIcon-cameraadd'></text>
					</view>
				</view>
			</view>
			<button type="primary" class="but" lang="lalla" @click="fabu">发布</button>
		</form>
		<tabbar></tabbar>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				src: '',
				imgList: [],
				img: [],
				modalName: null,
				videoContext: "",
				title: "",
				content: "",
				info: ""
			}
		},
		onShow() {
			let islogin = uni.getStorageSync('islogin')

			if (!islogin) {
				let that = this
				uni.showModal({
					title: "未登录不能发帖",
					cancelText: "返回首页",
					confirmText: "去登录",
					success: function(res) {
						if (res.confirm) {  
							uni.navigateTo({
								url: "../login/login"
							})
						} else if (res.cancel) {
							that.$store.commit('changePage', 0)
							uni.navigateTo({
								url: "../index/index"
							})
						}
					}
				})
			} else {
				this.info = uni.getStorageSync('userPhone') || uni.getStorageSync('userWx');
				console.log(this.info);
				this.$store.dispatch('initcheck')
			}
		},
		onReady: function(res) {
			this.videoContext = uni.createVideoContext('myVideo')
			uni.setNavigationBarTitle({
				title: '发布帖子'
			});

		},
		computed: {
			num() {
				return (parseInt(this.imgList.length) + parseInt(this.src.length ? 1 : 0))
			}
		},
		methods: {
			ChooseImage() {
				const that = this;
				this.src.length ? this.itemList = ['图片'] : null
				uni.showActionSheet({
					title: "选择上传类型",
					itemList: ['图片', '视频'],
					success: (res) => {
						console.log(res)
						if (res.tapIndex == 0) {
							uni.chooseImage({
								count: 4, //默认9 
								sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
								sourceType: ['album', 'camera'], //从相册选择
								success: async (res) => {
									if (that.imgList.length != 0) {
										that.imgList = that.imgList.concat(res.tempFilePaths);

									} else {
										that.imgList = res.tempFilePaths
									}
								}
							})
						} else {
							uni.chooseVideo({
								maxDuration: 30,
								sourceType: ['camera', 'album'],
								success: (res) => {
									console.log(res.tempFilePath);
									that.src = res.tempFilePath;
								}
							})
						}
					}
				})
			},
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			play() {
				this.videoContext.requestFullScreen()
			},
			ViewVideo() {
				this.videoContext.requestFullScreen()
			},
			DelImg(e) {
				uni.showModal({
					title: '提示',
					content: '是否要删除该图片？',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							this.imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
			Delvideo() {
				uni.showModal({
					title: '提示',
					content: '是否要删除该视频？',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							this.src = ""
						}
					}
				})
			},

			fabu() {
				if (!this.title || !this.content) {
					uni.showToast({
						title: "标题或者内容必填",
						icon: "none"
					})
					return;
				}
				uni.showModal({
					title: '提示',
					content: '是否确定发布？',
					success: async (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: "发布中"
							})
							let a =  this.imgList && await Promise.all(this.imgList.map(async (item) => {
								return await uniCloud.uploadFile({
									filePath: item,
								})
							}));
							a.map(item=>{
								this.img.push(item.fileID)
							})
							this.src && uniCloud.uploadFile({
								filePath: this.src,
								success: (res) => {
									this.src = res.fileID
								},
								fail: () => {
									uni.showToast({
										title: "上传失败请重试"
									})
									return;
								}
							})
							setTimeout(() => {
								this.submit()
							}, 1000)
						}
					}
				});
			},
			submit() {
				let mode = this.imgList.length > 2 ? 'more' : 'one';
				let data = {
					video: this.src,
					title: this.title,
					content: this.content,
					pic: this.img,
					time: new Date().getTime(),
					mode: this.imgList.length == 0 ? 'no' : mode,
					ok: this.$store.state.audit ? 0 : 1,
					name: this.info.name,
					avatar: this.info.atr,
					u_id:this.info.id //用户id
				}
				let msg = this.$store.state.audit ? '发布成功,等待管理员审核' : "发布成功"
				let that = this
				uniCloud.callFunction({
					name: "fatie",
					data: data,
					success(res) {
						uni.showToast({
							title: msg
						})
						uni.hideLoading();
						setTimeout(function() {
							that.$store.commit('changePage', 0)
							uni.redirectTo({
								url: "../index/index"
							})
						}, 500);
					},
					fail(err) {
						uni.hideLoading();
						uni.showToast({
							title: "发布失败请重试"
						})
					}
				})
			}
		}
	}
</script>

<style lang=scss>
	.but {
		margin-top: 5%;
	}

	.video {
		width: 100%;
		height: 100px;
	}
</style>
